import os,sys
import time,datetime
import re
import configparser
import pyautogui, psutil,pyperclip
import smtplib
from email.mime.text import MIMEText

# 设置监测目录和关键字
log_dir = "D:\Ax\OQ联测\安信OneQuant测试版新协议交易端2.5.6\Log"

扫描间隔=1

#  读取配置文件信息
pyPath=os.path.dirname(os.path.realpath(sys.argv[0]))
config = configparser.ConfigParser()
config.read(os.path.join(pyPath,'testConfig.ini'),encoding='utf-8')   # 读取config.ini
acc=config.get("OQ", "acc")
code=config.get("OQ", "code")
OQDir=config.get("OQ", "OQDir")
扫描间隔=config.getint("OQ", "scanTimeMin")
log_dir=os.path.join(OQDir,"Log")

# 生成错误信息字典
errorInfo=config.get("error", "errorInfo")
errorReason=config.get("error", "errorReason")
错误信息列表=errorInfo.split(",")
错误原因列表=errorReason.split(",")

错误原因字典=dict(zip(错误信息列表, 错误原因列表))

# 判断日志文件名
DMA算法文件名="DMALOG"+datetime.date.today().strftime("%Y%m%d")+".txt"
DMA算法日志路径=os.path.join(os.path.join(log_dir,"DMA_Import"),DMA算法文件名)
算法单导入文件名="ASOLOG"+datetime.date.today().strftime("%Y%m%d")+".txt"
算法单导入日志路径=os.path.join(os.path.join(log_dir,"AlgoScanOrder_Import"),算法单导入文件名)


# 定义日志文件扫描函数
def scan_log_files(日志路径,keywordDict,定时分钟=0.2):
    # 获取上次扫描的位置
    last_position = 0
    while True:
        # 日初首次启动,生成对应日志文件，间接判断启动OQ成功
        if not os.path.exists(日志路径):
            print("OQ客户端没有启动成功,没有生成当天的日志文件")
        else:
            # 扫描日志文件
            with open(日志路径, "r") as f:
                if last_position:
                    f.seek(last_position)
                while True:
                    line=f.readline()
                    # 检查是否出现关键字
                    for 关键字,报错原因 in keywordDict.items():
                        if re.search(关键字, line):
                            # 发送邮件告警
                            print(f"{报错原因}")
                            # send_email("Log File Alert", f"Keyword '{keyword}' found in log file '{log_file}' at position {f.tell()}")
                        last_position = f.tell()

        # 等待一段时间后重新扫描
        time.sleep(定时分钟*60)

def 自动启动OQ(路径,账号,密码):
    client_name="AxOneQuant.exe"
    for proc in psutil.process_iter():
        try:
            if proc.name() == client_name:
                os.system(r'taskkill /F /IM {}'.format(client_name))
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    os.startfile(os.path.join(路径,client_name))
    time.sleep(10)
    client_pid = None
    for proc in psutil.process_iter():
        if proc.name() == client_name:
            client_pid = proc.pid
            break
    if client_pid and psutil.pid_exists(client_pid):
        psutil.Process(client_pid).nice(psutil.HIGH_PRIORITY_CLASS)
    等待时间=1
    pyautogui.press("tab")
    time.sleep(等待时间)
    pyautogui.press("tab")
    time.sleep(等待时间)
    pyautogui.press('shift')
    pyautogui.typewrite(账号)
    time.sleep(等待时间)
    pyautogui.press("tab")
    time.sleep(等待时间)
    pyautogui.typewrite(密码)
    time.sleep(等待时间)
    pyautogui.press('enter')


def toCSVFormat(order_elements):
    # if 类型=="DMA算法":
    #     order_elements=[self.updTime
    #         ,self.custBatchNo
    #         ,self.acctType
    #         ,self.acct
    #         ,self.symbol
    #         ,self.tradeSide
    #         ,self.targetQty
    #         ,self.algoId
    #         ,self.priceType
    #         ,self.ticks
    #         ,self.highLimitPrice
    #         ,self.lowLimitPrice
    #         ]
    # elif 类型=="DMA算法":
    #     order_elements=[self.updTime
    #         ,self.custAlgoNo
    #         ,self.acctType
    #         ,self.acct
    #         ,self.symbol
    #         ,self.tradeSide
    #         ,self.targetVol
    #         ,self.targetAmt
    #         ,self.algoId
    #         ,self.algoParam
    #         ]
    order_str = ",".join([str(ele) for ele in order_elements])
    return order_str

def 初始化文件(类型,路径):
    if not os.path.exists(路径):
        if 类型="DMA算法":
            with open(路径,'w') as f:
                f.write("updTime,custBatchNo,acctType,acct,symbol,tradeSide,targetQty,algoId,priceType,ticks,highLimitPrice,lowLimitPrice" + "\n")
            print('创建DMA下单文件:' + 路径)
        elif 类型="算法单导入":
            with open(路径,'w') as f:
                f.write("updTime,custAlgoNo,acctType,acct,symbol,tradeSide,targetVol,targetAmt,algoId,algoParam + "\n")
            print('创建算法单导入下单文件:' + 路径)



def 定时写入文件单(算法类型,扫单路径,写入间隔):
     # 初始化下单文件
    date= datetime.datetime.now().strftime("%Y%m%d")
    if 算法类型=="DMA类型":
        OrderFile =os.path.join(扫单路径,'algoOrder_' + date + '.csv')
    elif 算法类型=="算法单导入":
        OrderFile =os.path.join(扫单路径,'algoStart_' + date + '.csv')
    if not os.path.exists(OrderFile):
        print("OQ扫单功能没有启动成功,没有生成当天的扫单文件")

    else:


自动启动OQ(OQDir,acc,code)
time.sleep(10)
# 启动日志文件扫描程序
scan_log_files(DMA算法日志路径,错误原因字典,扫描间隔)
scan_log_files(算法单导入日志路径,错误原因字典,扫描间隔)

